package com.mike.server.engine;

import java.util.concurrent.ConcurrentLinkedQueue;

import com.mike.server.GameServer;
import com.mike.server.support.BaseService;
import com.mike.server.system.chat.ChatService;
import com.mike.server.system.group.GroupService;
import com.mike.server.system.mail.MailService;
import com.mike.server.system.map.MapService;
import com.mike.server.system.role.RoleService;

/**
 * 游戏各系统服务线程分发线程池
 * @author <a href="zhaoming23@gmail.com"> Mike </a>
 * @version 1.0
 * 2011-4-4 下午05:02:34
 */
public class ServiceDispatherThread implements Runnable {

	private static ServiceDispatherThread instance = new ServiceDispatherThread();
	
	private ConcurrentLinkedQueue<IGameMessage> messageQueue = new ConcurrentLinkedQueue<IGameMessage>();
	
	private ServiceDispatherThread() {
		//Don't allow new it outside.
		//test();
	}
	
	@SuppressWarnings("unused")
	private void test() {
		/*for (int i = 0; i < 11100; i++) {
			messageQueue.add(new BaseGameMessage(IGameMessage.CHAT_SYSTEM));
			messageQueue.add(new BaseGameMessage(IGameMessage.MAIL_SYSTEM));
			messageQueue.add(new BaseGameMessage(IGameMessage.MAP_SYSTEM));
			messageQueue.add(new BaseGameMessage(IGameMessage.GROUP_SYSTEM));
			messageQueue.add(new BaseGameMessage(IGameMessage.ROLE_SYSTEM));
		}*/
	}

	public static ServiceDispatherThread getInstance() {
		return instance;
	}
	
	public void addMessage(IGameMessage incomingMessage) {
		if(null != incomingMessage) {
			messageQueue.add(incomingMessage);
		}
	}
	
	@Override
	public void run() {
		while(true) {
			if(!GameServer.getInstanse().isInited()) continue;
			final IGameMessage m = messageQueue.poll();
			if(null != m) {
				BaseService baseService = null;
					//根据类型即所属模块分发游戏消息
					switch (m.getType()) {
						case IGameMessage.CHAT_SYSTEM:
							ChatService.getInstance().addMesage(m);
							baseService = ChatService.getInstance();
							break;
						case IGameMessage.MAIL_SYSTEM:
							MailService.getInstance().addMesage(m);
							baseService = MailService.getInstance();
							break;
						case IGameMessage.ROLE_SYSTEM:
							RoleService.getInstance().addMesage(m);
							baseService = RoleService.getInstance();
							break;
						case IGameMessage.MAP_SYSTEM:
							MapService.getInstance().addMesage(m);
							baseService = MapService.getInstance();
							break;
						case IGameMessage.GROUP_SYSTEM:
							GroupService.getInstance().addMesage(m);
							baseService = GroupService.getInstance();
							break;
					}
				if(null != baseService) {
					//再由各模块处理线程池具体处理相关逻辑
					ServiceThreadPool.getInstance().exe(baseService);
				}
			}
			
			if(messageQueue.size() <= 0) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
			}
		}
	}
	
}
